package cn.tellfish.studydemo.demo;

import java.util.Random;
import java.util.concurrent.Semaphore;

//计数信号量
public class SemaphoreTest {

    private Semaphore sp = new Semaphore(10, true);
    private Random rd = new Random();
    private int waitTime = 10000;

    public void useCar() throws InterruptedException {
        System.out.println(Thread.currentThread().getName() + "需要用车");
        long start = System.currentTimeMillis();
        sp.acquire();
        System.out.println(Thread.currentThread().getName() + "许可用车，等待了" + (System.currentTimeMillis() - start));
        try {
            Thread.sleep(rd.nextInt(waitTime));
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName() + "用车完毕");
            sp.release();
        }
    }

    public static void main(String[] args) {
        Random rd = new Random();
        SemaphoreTest demo = new SemaphoreTest();
        for (int i = 0; i < 20; i++) {
            new Thread(() -> {
                try {
                    Thread.sleep(rd.nextInt(5000));
                    demo.useCar();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }, "用户" + i).start();
        }
    }

}
